<template>
  <div class="dish-management-container">
    <div class="page-header">
      <h1>菜品管理</h1>
      <el-button type="primary" @click="showAddDialog = true">
        <i class="el-icon-plus"></i> 添加菜品
      </el-button>
    </div>

    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索菜品名称..."
        style="width: 300px; margin-right: 10px;"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <div class="dishes-table" v-loading="loading">
      <el-table :data="dishes" style="width: 100%">
        <el-table-column prop="dishid" label="ID" width="80" />
        <el-table-column label="图片" width="120">
          <template slot-scope="scope">
            <img 
              :src="scope.row.dishcover || require('@/assets/dishes/dish1.jpg')" 
              :alt="scope.row.dishname"
              style="width: 80px; height: 60px; object-fit: cover; border-radius: 4px;"
            >
          </template>
        </el-table-column>
        <el-table-column prop="dishname" label="菜品名称" />
        <el-table-column prop="dishprice" label="价格" width="100">
          <template slot-scope="scope">¥{{ scope.row.dishprice }}</template>
        </el-table-column>
        <el-table-column prop="dishdescribe" label="描述" show-overflow-tooltip />
        <el-table-column prop="dishdiff" label="类别" width="100" />
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="editDish(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteDish(scope.row.dishid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>

    <!-- 添加/编辑菜品对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="showAddDialog"
      width="600px"
    >
      <el-form :model="dishForm" :rules="dishRules" ref="dishForm" label-width="100px">
        <el-form-item label="菜品名称" prop="dishname">
          <el-input v-model="dishForm.dishname" placeholder="请输入菜品名称"></el-input>
        </el-form-item>
        
        <el-form-item label="菜品价格" prop="dishprice">
          <el-input-number 
            v-model="dishForm.dishprice" 
            :min="0" 
            :precision="2"
            placeholder="请输入价格"
          ></el-input-number>
        </el-form-item>
        
        <el-form-item label="菜品描述" prop="dishdescribe">
          <el-input 
            v-model="dishForm.dishdescribe" 
            type="textarea" 
            :rows="3"
            placeholder="请输入菜品描述"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="菜品类别" prop="dishdiff">
          <el-select v-model="dishForm.dishdiff" placeholder="请选择类别">
            <el-option label="荤菜" value="荤"></el-option>
            <el-option label="素菜" value="素"></el-option>
            <el-option label="汤类" value="汤"></el-option>
            <el-option label="主食" value="主食"></el-option>
            <el-option label="饮品" value="饮品"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="菜品图片" prop="dishcover">
          <el-upload
            class="dish-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="dishForm.dishcover" :src="dishForm.dishcover" class="dish-image">
            <i v-else class="el-icon-plus dish-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <div slot="footer">
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDish" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDishesByStore, addDish, updateDish, deleteDish } from '@/api/dish'
import { mapGetters } from 'vuex'

export default {
  name: 'DishManagement',
  data() {
    return {
      loading: false,
      submitting: false,
      dishes: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchKeyword: '',
      showAddDialog: false,
      editingDish: null,
      dishForm: {
        dishname: '',
        dishprice: 0,
        dishdescribe: '',
        dishdiff: '',
        dishcover: '',
        storeid: null
      },
      dishRules: {
        dishname: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        dishprice: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' }
        ],
        dishdiff: [
          { required: true, message: '请选择菜品类别', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    
    dialogTitle() {
      return this.editingDish ? '编辑菜品' : '添加菜品'
    },
    
    uploadUrl() {
      return '/dish/upload'
    }
  },
  mounted() {
    this.loadDishes()
  },
  methods: {
    async loadDishes() {
      this.loading = true
      try {
        const params = {
          storeid: this.userInfo.storeid || 1, // 假设用户有店铺ID
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword
        }
        
        const response = await getDishesByStore(params)
        if (response.data && response.data.code === 20000) {
          this.dishes = response.data.data.list || []
          this.total = response.data.data.total || 0
        } else {
          // 使用模拟数据
          this.loadMockDishes()
        }
      } catch (error) {
        console.error('加载菜品失败:', error)
        this.loadMockDishes()
      } finally {
        this.loading = false
      }
    },

    loadMockDishes() {
      this.dishes = [
        {
          dishid: 1,
          dishname: '肉末豆腐',
          dishprice: 44.00,
          dishdescribe: '好吃',
          dishdiff: '荤',
          dishcover: 'https://shanfood.oss-cn-chengdu.aliyuncs.com/elema/upload/2025-06-29/e89fef7cf745431a81358d530abc4bf0.jpg'
        },
        {
          dishid: 2,
          dishname: '宫保鸡丁',
          dishprice: 38.00,
          dishdescribe: '经典川菜',
          dishdiff: '荤',
          dishcover: 'https://shanfood.oss-cn-chengdu.aliyuncs.com/elema/upload/2025-06-29/e89fef7cf745431a81358d530abc4bf0.jpg'
        }
      ]
      this.total = this.dishes.length
    },

    handleSearch() {
      this.currentPage = 1
      this.loadDishes()
    },

    resetSearch() {
      this.searchKeyword = ''
      this.currentPage = 1
      this.loadDishes()
    },

    handlePageChange(page) {
      this.currentPage = page
      this.loadDishes()
    },

    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadDishes()
    },

    editDish(dish) {
      this.editingDish = dish
      this.dishForm = { ...dish }
      this.showAddDialog = true
    },

    async deleteDish(dishId) {
      try {
        await this.$confirm('确定要删除这个菜品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteDish(dishId)
        if (response.data && response.data.code === 20000) {
          this.$message.success('删除成功')
          this.loadDishes()
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除菜品失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    handleImageSuccess(response) {
      if (response.code === 20000) {
        this.dishForm.dishcover = response.data
        this.$message.success('图片上传成功')
      } else {
        this.$message.error('图片上传失败')
      }
    },

    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },

    async submitDish() {
      try {
        await this.$refs.dishForm.validate()
        
        this.submitting = true
        
        const dishData = {
          ...this.dishForm,
          storeid: this.userInfo.storeid || 1
        }
        
        let response
        if (this.editingDish) {
          response = await updateDish(dishData)
        } else {
          response = await addDish(dishData)
        }
        
        if (response.data && response.data.code === 20000) {
          this.$message.success(this.editingDish ? '更新成功' : '添加成功')
          this.showAddDialog = false
          this.loadDishes()
        } else {
          this.$message.error(response.data?.msg || '操作失败')
        }
      } catch (error) {
        console.error('提交菜品失败:', error)
        this.$message.error('操作失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dish-management-container {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      margin: 0;
      font-size: 24px;
      color: #333;
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 4px;
  }

  .dishes-table {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .pagination-wrapper {
      margin-top: 20px;
      text-align: center;
    }
  }

  .dish-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #409EFF;
    }

    .dish-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .dish-image {
      width: 178px;
      height: 178px;
      display: block;
      object-fit: cover;
    }
  }
}
</style> 